package fr.lna.chess.util;

import java.awt.Image;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.swing.Icon;
import javax.swing.ImageIcon;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import fr.lna.chess.type.IMAGE;
import fr.lna.chess.type.ImageManager;
import fr.lna.util.MessageTools;

/**
 * Classe pour la gestion des images
 * @author bull
 *
 */
@Component("image.source")
public class ImageManagerImpl implements ImageManager {

	  /** Buffer des icônes en cours d'utilisation. */
	private static final Map<IMAGE, ImageIcon> ICONS = new HashMap<IMAGE, ImageIcon>();

	protected Logger log = Logger.getLogger(getClass());
	
	@Override
	public ImageIcon getImage(IMAGE name) {
		ImageIcon res = ICONS.get(name);
		if (res == null)
		{
		  String fileName = getFileName(name);
		  final URL url = getClass().getResource(fileName);
		  if (url == null)
		  {
		    log.warn("ImageIcon [" + name + "] not found");
		  }
		  else
		  {
		    res = new ImageIcon(getClass().getResource(fileName));
		    ICONS.put(name, res);
		  }
		}
		return res;
	}

	/**
	 * Retourne le nom de l'image
	 * @param name
	 * @return
	 */
	private String getFileName(IMAGE name) {
		String nameFile = MessageTools.genCode(name, "",'-') + name.getTaille()+"."+name.getType();
		return "/ressources/skin/defaut/"+nameFile;
	}

	@Override
	public Icon getImageIcon(IMAGE name) {
		ImageIcon img = getImage(name);
		return img;
	}

}
